package cn.iocoder.yudao.module.trade.order.service.calculator;

import cn.iocoder.yudao.module.api.infrastructure.config.dto.MemberConfigRespDTO;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeOrderTypeEnum;
import cn.iocoder.yudao.module.trade.order.bo.TradePriceCalculateReqBO;
import cn.iocoder.yudao.module.trade.order.bo.TradePriceCalculateRespBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;

/**
 * 赠送分红的 {@link TradePriceCalculator} 实现类
 * 必须在 {@link TradeCryptocurrencyDeductPriceCalculator} 之后
 *
 * @author 山野羡民
 */
@Component
@Order(TradePriceCalculator.ORDER_BONUS_GIVE)
@Slf4j
public class TradeBonusGiveCalculator implements TradePriceCalculator {

    @Override
    public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
        // 1.0 校验支付金额及联盟豆抵扣
        if (!Objects.equals(result.getType(), TradeOrderTypeEnum.CRYPTOCURRENCY.getType())) {
            log.debug("[calculate][不是联盟豆全额抵扣，不计算赠送分红]");
            return;
        }
        // 1.1 校验分红功能是否可用
        MemberConfigRespDTO config = result.getMemberConfig();
        if (config == null) {
            log.debug("[calculate][未获取到用户中心配置，计算赠送分红不生效]");
            return;
        }
        double cryptocurrencyToBonusPercent = config.getCryptocurrencyToBonusPercent();
        if (cryptocurrencyToBonusPercent <= 0) {
            log.debug("[calculate][设置赠送的分红百分比无效]");
            return;
        }
        // 2.1 计算赠送分红
        int giveBonus = (int) (result.getDeductCryptocurrency().intValue() * cryptocurrencyToBonusPercent / 100);
        if (giveBonus == 0) {
            log.warn("[calculate][计算赠送分红为0] payCryptocurrencyIncrement={}, cryptocurrencyToBonusPercent={}", result.getDeductCryptocurrency(), cryptocurrencyToBonusPercent);
            return;
        }
        // 2.2 计算分摊的赠送分红
        List<TradePriceCalculateRespBO.OrderItem> orderItems = filterList(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSelected);
        List<Integer> divideBonus = TradePriceCalculatorHelper.dividePrice(orderItems, giveBonus);

        // 3.2 更新 SKU 赠送分红
        for (int i = 0, n = orderItems.size(); i < n; i++) {
            TradePriceCalculateRespBO.OrderItem orderItem = orderItems.get(i);
            // 产品可能赠送了分红，所以这里要加上
            orderItem.setGiveBonus(orderItem.getGiveBonus() + divideBonus.get(i));
        }
        // 3.3 更新订单赠送分红
        TradePriceCalculatorHelper.recountAllGiveBonus(result);
        log.debug("[calculate][分红赠送计算完成] {}", result.getPrice());
    }

}
